import oss2
from django.conf import settings
import uuid

def upload_to_cloud_storage(image_file):
    """上传文件到阿里云OSS
    Args:
        image_file: Django的File对象或文件类对象
    Returns:
        图片的公开URL
    """
    # 初始化OSS客户端
    auth = oss2.Auth(
        settings.OSS_ACCESS_KEY_ID,
        settings.OSS_ACCESS_KEY_SECRET
    )
    bucket = oss2.Bucket(
        auth,
        settings.OSS_ENDPOINT,  # 如: "https://oss-cn-hangzhou.aliyuncs.com"
        settings.OSS_BUCKET_NAME
    )

    # 生成唯一文件名
    file_ext = image_file.name.split('.')[-1]
    object_name = f"idcards/{uuid.uuid4()}.{file_ext}"

    # 上传文件
    bucket.put_object(object_name, image_file)

    # 返回公开URL（需确保Bucket为公共读或设置CDN域名）
    return f"https://{settings.OSS_BUCKET_NAME}.{settings.OSS_ENDPOINT}/{object_name}"